<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="流程名称" prop="definitionName">
          <el-input
            v-model="queryParams.definitionName"
            placeholder="请输入流程名称"
            style="width: 240px"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审批状态" prop="approvalStatus">
          <el-select v-model="queryParams.approvalStatus" placeholder="请选择审批状态" style="width: 240px" clearable>
            <el-option
              v-for="dict in dict.type.apply_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="daterangeApplyTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['flowable:applyrecord:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="applyrecordList" :header-cell-style="{'text-align':'center'}" @selection-change="handleSelectionChange" >
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="序号" width="55" align="center">
          <template slot-scope="scope">
            <span>{{ (pageParams.current-1)*pageParams.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="流程名称" align="center" prop="definitionName" />
        <el-table-column label="流程版本" align="center" width="80px">
          <template slot-scope="scope">
            <el-button type="text" @click="handleProcessView(scope.row)">
              <el-tag size="medium" >{{ scope.row.definitionVersion }}</el-tag>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="approvalStatus">
          <template slot-scope="scope">
            <el-tag size="medium" :type="handleApprovalStatus(scope.row)">
              <dict-tag :options="dict.type.apply_status" :value="scope.row.approvalStatus"/>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="applyTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批完成时间" align="center" prop="approvalCompleteTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.approvalCompleteTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请摘要" align="left" prop="summary" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="left" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.approvalStatus==='0'"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['flowable:applyrecord:edit']"
            >修改/提交</el-button>
            <el-button v-if="scope.row.approvalStatus!=='0'&&scope.row.approvalStatus!=='5'"
              type="text"
              size="mini"
              icon="el-icon-tickets"
              @click="handleFlowRecord(scope.row)"
              v-hasPermi="['workflow:process:startList']"
            >详情</el-button>
            <el-button v-if="scope.row.approvalStatus==='4'"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRevoke(scope.row)"
              v-hasPermi="['flowable:applyrecord:remove']"
            >撤回</el-button>
            <el-button v-if="scope.row.approvalStatus==='3'||scope.row.approvalStatus==='5'"
              type="text"
              size="mini"
              icon="el-icon-refresh-right"
              v-hasPermi="['workflow:process:startList']"
              @click="handleAgain(scope.row)"
            >再次申请</el-button>
            <el-button v-if="scope.row.approvalStatus==='0'||scope.row.approvalStatus==='5'"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['flowable:applyrecord:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageParams.current"
        :limit.sync="pageParams.size"
        @pagination="getList"
      />

      <!-- 流程图 -->
      <el-dialog :title="processView.title" :visible.sync="processView.open" width="70%" append-to-body>
        <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{height: '400px'}" />
      </el-dialog>
    </div>
  </template>
  
  <script>
  import {listApplyrecord,  delApplyrecord, revokeApplyrecord } from "@/api/workflow/applyrecord";
  import {getBpmnXml, getProcessExternalForm } from '@/api/workflow/process';
  import ProcessViewer from '@/components/ProcessViewer';

  export default {
    name: "Applyrecord",
    components: {
      ProcessViewer
    },
    dicts: ['apply_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 我的流程表格数据
        applyrecordList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 审批完成时间时间范围
        daterangeApplyTime: [],
        // 审批完成时间时间范围
        daterangeApprovalCompleteTime: [],
        // 分页参数
        pageParams: {
          current: 1,
          size: 10,
        },
        // 查询参数
        queryParams: {
          id: null,
          deptNames: null,
          categoryName: null,
          definitionName: null,
          approvalStatus: null,
          applyTime: null,
          approvalCompleteTime: null,
          beginApplyTime: null,
          endApplyTime: null,
        },
        categoryProps: {
          label: 'categoryName',
          value: 'code'
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        processView: {
          title: '',
          open: false,
          index: undefined,
          xmlData:"",
        }
      };
    },
    created() {
      
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.handleQuery()
      })
    },
    methods: {
      /** 搜索按钮操作 */
      handleQuery() {
        this.pageParams.current = 1;
        this.getList();
      },
      /** 查询我的流程列表 */
      getList() {
        this.loading = true;
        if (null != this.daterangeApplyTime && '' != this.daterangeApplyTime) {
          this.queryParams["beginApplyTime"] = this.daterangeApplyTime[0];
          this.queryParams["endApplyTime"] = this.daterangeApplyTime[1];
        } else {
          this.queryParams["beginApplyTime"] = null;
          this.queryParams["endApplyTime"] = null;
        }
        listApplyrecord(this.pageParams,this.queryParams).then(response => {
          this.applyrecordList = response.page.records;
          this.total = response.page.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          userId: null,
          userName: null,
          nickName: null,
          deptIds: null,
          deptNames: null,
          categoryId: null,
          categoryName: null,
          definitionId: null,
          definitionName: null,
          deployId: null,
          processInstanceId: null,
          formId: null,
          bussinessKey: null,
          summary: null,
          remarks: null,
          approvalStatus: null,
          applyTime: null,
          approvalCompleteTime: null,
          createTime: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeApplyTime = [];
        this.daterangeApprovalCompleteTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      //复选框是否可用
      selectable(row) {
        //草稿、撤回的申请可删除
        if(row.approvalStatus==='0'||row.approvalStatus==='5') {
          return true;
        }else {
          return false;
        }
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        getProcessExternalForm({
          definitionId: row.definitionId,
          deployId: row.deployId
        }).then(res => {
          if (res.code==='200') {
            //缓存参数
            let queryParams = {
              definitionId: row.definitionId,
              procInsId: row.procInsId,
              deployId: row.deployId,
              businessKey: row.businessKey,
              showApproval: false,
              processed: false,
              fillAgain: true
            };
            window.localStorage.setItem("flowableDetailParams",JSON.stringify(queryParams));

            //跳转表单路由，显示表单填写页面
            const formUrl = res.data.formUrl;
            this.$router.push({
              path: `${formUrl}`
            })
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        var ids = this.ids;
        if(row.id){
          ids = new Array();
          ids.push(row.id);
        }
        this.$modal.confirm('是否确认删除选定的数据项？').then(function() {
          return delApplyrecord(ids);
        }).then((res) => {
          if(res.code==='200'){
            this.handleQuery();
            this.$modal.msgSuccess(res.msg);
          }else{
            this.$modal.msgError(res.msg);
          }
        });
      },
      /** 撤回按钮操作 */
      handleRevoke(row) {
        this.$modal.confirm('确认撤回申请记录吗？').then(function() {
          return revokeApplyrecord(row.id);
        }).then((res) => {
          if(res.code==='200'){
            this.handleQuery();
            this.$modal.msgSuccess(res.msg);
          }else{
            this.$modal.msgError(res.msg);
          }
        });
      },
      /** 查看流程图 */
      handleProcessView(row) {
        let definitionId = row.definitionId;
        this.processView.title = "流程图";
        this.processView.index = definitionId;
        // 发送请求，获取xml
        getBpmnXml(definitionId).then(res => {
          this.processView.xmlData = res.data;
        })
        this.processView.open = true;
      },
      /** 流程流转记录 */
      handleFlowRecord(row) {
        getProcessExternalForm({
          definitionId: row.definitionId,
          deployId: row.deployId
        }).then(res => {
          if (res.code==='200') {
            //缓存参数
            let queryParams = {
              procInsId: row.processInstanceId,
              deployId: row.deployId,
              businessKey: row.businessKey,
              showApproval: false
            };
            window.localStorage.setItem("flowableDetailParams",JSON.stringify(queryParams));

            const formUrl = res.data.formUrl;
            //跳转表单路由，显示表单填写页面
            this.$router.push({
              path: `${formUrl}`
            })
          }
        })
      },
      /** 重新发起 */
      handleAgain(row) {
        getProcessExternalForm({
          definitionId: row.definitionId,
          deployId: row.deployId
        }).then(res => {
          if (res.code==='200') {
            let newRecord = true;
            //撤回状态的再次申请更新原申请记录
            if(row.approvalStatus==='5'){
              newRecord = false;
            }
            //缓存参数
            let queryParams = {
              definitionId: row.definitionId,
              procInsId: row.procInsId,
              deployId: row.deployId,
              businessKey: row.businessKey,
              showApproval: false,
              processed: false,
              fillAgain: true,
              newRecord: newRecord
            };
            window.localStorage.setItem("flowableDetailParams",JSON.stringify(queryParams));

            //跳转表单路由，显示表单填写页面
            const formUrl = res.data.formUrl;
            this.$router.push({
              path: `${formUrl}`
            })
          }
        })
      },
      handleApprovalStatus(row) {
        if(row.approvalStatus==='2') {
          //审批通过
          return "success";
        }else if(row.approvalStatus==='3') {
          //审批驳回
          return "danger";
        }else if(row.approvalStatus==='1') {
          //审批中、待审批
          return "default";
        }else if(row.approvalStatus==='5') {
          //审批撤回
          return "warning";
        }else {
          return "info";
        }
      }
    }
  };
  </script>
  